package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.TbMessageMapper;
import com.zhentao.pojo.TbMessage;
import com.zhentao.service.TbMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

@Service
public class TbMessageServiceImpl extends ServiceImpl<TbMessageMapper, TbMessage> implements TbMessageService {

    @Value("${stu.base-url:http://localhost:1001}")
    private String stuBaseUrl;

    @Override
    public List<TbMessage> listByReceiver(Long receiverId, Integer receiverType) {
        QueryWrapper<TbMessage> qw = new QueryWrapper<>();
        qw.eq("receiver_id", receiverId)
          .eq("receiver_type", receiverType)
          .orderByDesc("send_time");
        return this.list(qw);
    }

    @Override
    public boolean sendMessage(TbMessage message) {
        if (message.getSendTime() == null) {
            message.setSendTime(new Date());
        }
        if (message.getIsRead() == null) {
            message.setIsRead(0);
        }
        boolean saved = this.save(message);
        // 保存后尝试向学生端推送（不影响主流程）
        try {
            RestTemplate rt = new RestTemplate();
            ResponseEntity<String> res = rt.postForEntity(stuBaseUrl + "/push/message", message, String.class);
        } catch (Exception ignored) {}
        return saved;
    }

    @Override
    public boolean markRead(Long messageId) {
        TbMessage msg = this.getById(messageId);
        if (msg == null) return false;
        msg.setIsRead(1);
        return this.updateById(msg);
    }
}